package com.lsh.oms.worker.service.task;

import com.alibaba.fastjson.JSON;
import com.lsh.base.common.json.JsonUtils;
import com.lsh.base.common.model.CommonResult;
import com.lsh.base.lang.Maps;
import com.lsh.oms.core.constant.ReturnCode;
import com.lsh.oms.core.enums.OrderStatus;
import com.lsh.oms.core.enums.TaskStatus;
import com.lsh.oms.core.enums.TaskType;
import com.lsh.oms.core.exception.BusinessException;
import com.lsh.oms.core.exception.ExceptionStatus;
import com.lsh.oms.core.model.order.OrderHead;
import com.lsh.oms.core.model.po.OmsTask;
import com.lsh.oms.core.proxy.service.TmsProxy;
import com.lsh.oms.core.service.order.OrderQueryService;
import com.lsh.oms.core.service.order.frozen.OrderReceiptFrogenService;
import com.lsh.oms.worker.service.base.OmsSimpleElasticJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * Project Name: lsh-oms
 *
 * @author peter
 * @date 18/12/14
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Slf4j
@Component
public class OrderReceiptDealTask extends OmsSimpleElasticJob {

    @Autowired
    private OrderQueryService orderQueryService;

    @Autowired
    private OrderReceiptFrogenService orderReceiptFrogenService;

    @Autowired
    private TmsProxy tmsProxy;


    @Override
    protected Integer getFetchSize() {
        return 20;
    }

    @Override
    protected TaskType getTaskType() {
        return TaskType.ORDER_RECEIPT;
    }

    @Override
    protected List<Integer> dealTaskStatus() {

        return Arrays.asList(TaskStatus.TASK_UN_DEAL.getCode(), TaskStatus.TASK_DEAL_FAIL.getCode());
    }

    @Override
    protected int process(OmsTask omsTask) {
        String logSign = "logSign : 【jop:25:task】: " + omsTask.getRefCode();

        boolean dealFlag = false;
        try {
            OrderHead orderHead = this.checkPara(omsTask, logSign);

            if (orderHead.getOrderStatus().compareTo(OrderStatus.ORDER_SIGN.getIndex()) == 0) {
                return 1;
            }

            CommonResult commonResult = this.orderReceiptFrogenService.createReceiptFromShip(orderHead, logSign);

            log.info(logSign + " commonResult-receipt-" + omsTask.getRefCode() + JSON.toJSONString(commonResult));

            if (commonResult.getCode().equals(ReturnCode.REQUEST_SUCCESS)) {

                dealFlag = true;

                this.terminateTmsTask(orderHead);
            }
        } catch (BusinessException e) {

            log.error("业务异常code : " + e.getCode() + ",异常信息: " + e.getMessage(), e);
        } catch (Exception e) {

            log.error("业务异常code : " + ExceptionStatus.E3001001.getCode(), e);
        }

        return dealFlag == true ? 1 : -1;
    }

    private void terminateTmsTask(OrderHead order) {
        try {
            this.tmsProxy.terminateTask(Maps.of("other_id", order.getOrderCode()));
        } catch (Exception e) {
            log.info("" + order.getOrderCode() + " 通知tms签收失败");
        }
    }

    private OrderHead checkPara(OmsTask omsTask, String logSign) {

        log.info(logSign + ":签收入参 －－ {}", JsonUtils.obj2Json(omsTask));

        OrderHead orderHead = orderQueryService.findByCode(Long.valueOf(omsTask.getRefCode()), true, false);
        if (orderHead == null) {
            throw new BusinessException(ReturnCode.FIND_ORDER_IS_NULL, "用户订单号未查询到订单");
        }

        //签收发生在发货以后
        if (orderHead.getOrderStatus().compareTo(OrderStatus.ORDER_SORTING.getIndex()) < 0) {
            throw new BusinessException(ReturnCode.ORDER_STATUS_ERROR, "订单状态是" + OrderStatus.getName(orderHead.getOrderStatus()) + "，请检验。");
        }

        return orderHead;
    }

//    /**
//     * 处理失败邮件发送
//     *
//     * @param orderReceiptId 签收单号
//     * @param msg            错误信息
//     */
//    private void sendEmail(Long orderReceiptId, String msg) {
//        if (msg.length() > 200) {
//            msg = msg.substring(0, 200);
//        }
//        String message = orderReceiptId + " 签收单推送失败 " + msg;
//
//        this.sendEmailService.asyncSendEmail(message, "签收单进销存推送失败-" + DateUtil.formatTime(new Date()));
//    }


}
